﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using CivilleWP7.Civille.Source;
using System.Data.Services.Client;
using CivilleWP7.CivilleDataServiceReference;
using CivilleWP7.Views.Controls;
using SL.Phone.Federation.Utilities;
using Microsoft.Phone.Shell;
using System.Windows.Media.Imaging;

namespace CivilleWP7.Views.Pages
{
    public partial class FriendPage : PhoneApplicationPage
    {

        private static CivilleUser user;

        public static CivilleUser User
        {
            get { return FriendPage.user; }
            set { FriendPage.user = value; }
        }
        private bool IsLightTheme;
        public FriendPage()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(ExtrasPivotPage_Loaded);

            displayApplicationBar();
            setBackground();
        }
        void setBackground()
        {
            checkThemeColor();
            ImageBrush myBrush = new ImageBrush();
            if(IsLightTheme)
                myBrush.ImageSource=new BitmapImage(new Uri("/Resources/Images/Backgroundwhite.jpg",UriKind.Relative));
            else
                myBrush.ImageSource = new BitmapImage(new Uri("/Resources/Images/Background.jpg",UriKind.Relative));
            ContentPanel.Background=myBrush;
        }
        void checkThemeColor()
        {
            var visibility = (Visibility)Application.Current.Resources["PhoneLightThemeVisibility"];
            if (visibility == Visibility.Visible)
                IsLightTheme = true;
            else
                IsLightTheme = false;
        }
        void displayApplicationBar()
        {

            

            ApplicationBar = new ApplicationBar();
            ApplicationBar.IsVisible = true;
            ApplicationBar.IsMenuEnabled = true;
            
        }
        void addAddFriendButton()
        {
            checkThemeColor();
            ApplicationBarIconButton button1;
            if (IsLightTheme)
                button1 = new ApplicationBarIconButton(new Uri("/Resources/Icons/Light/appbar.new.rest.png", UriKind.Relative));
            else
                button1 = new ApplicationBarIconButton(new Uri("/Resources/Icons/Dark/appbar.new.rest.png", UriKind.Relative));
            button1.Text = "Add friend";
            button1.Click += new EventHandler(ApplicationBarIconButton_Click);
            ApplicationBar.Buttons.Add(button1);
        }
        void ExtrasPivotPage_Loaded(object sender, RoutedEventArgs e)
        {
            CivilleDataServiceConnector.SetGetFriendshipQueryParameters(UserContext.CurrentUser.ID, user.ID);
            CivilleDataServiceConnector.GetFriendshipQuery.BeginExecute(OnGetFriendshipCompleted, CivilleDataServiceConnector.GetFriendshipQuery);
            PageTitle.Text = user.FirstName;
            CivilleDataServiceConnector.SetLevelQueryParameters(user.CurrentLevel);
            CivilleDataServiceConnector.LevelQuery.BeginExecute(OnLevelQueryCompleted, CivilleDataServiceConnector.LevelQuery);
            TasksListBox.Items.Clear();
            CivilleDataServiceConnector.AllTasksQuery.BeginExecute(OnGetAllTasksCompleted, CivilleDataServiceConnector.AllTasksQuery);
        }

        private void OnGetAllTasksCompleted(IAsyncResult result)
        {
            Dispatcher.BeginInvoke(() =>
                {
                    List<Task> AllTasks = new List<Task>();
                    DataServiceQuery<Task> query=result.AsyncState as DataServiceQuery<Task>;
                    AllTasks = query.EndExecute(result).ToList();

                    CivilleDataServiceConnector.SetTaskHistoryParameters(user.ID);
                    CivilleDataServiceConnector.GetTaskHistory.BeginExecute((result2) => {

                        Dispatcher.BeginInvoke(() =>
                            {
                                DataServiceQuery<TaskHistory> query2 = result2.AsyncState as DataServiceQuery<TaskHistory>;
                                foreach (TaskHistory history in query2.EndExecute(result2))
                                {
                                    Task t = AllTasks.Where(x => x.ID == history.TaskID).First();
                                    CustomListItem listItem = new CustomListItem();
                                    listItem.TitleTxt.Text = t.Title;
                                    listItem.DescriptionTxt.Text = t.Description;
                                    listItem.CheckMarkImage.Source = new BitmapImage(new Uri(t.Logo, UriKind.RelativeOrAbsolute));
                                    listItem.CheckMarkImage.Width = 50;
                                    TasksListBox.Items.Add(listItem);
                                }
                            });
                    }, CivilleDataServiceConnector.GetTaskHistory);
                });
        }
        private void OnGetFriendshipCompleted(IAsyncResult result)
        {
            Dispatcher.BeginInvoke(() =>
                {
                    DataServiceQuery<CivilleUserToCivilleUser> query = result.AsyncState as DataServiceQuery<CivilleUserToCivilleUser>;
                    List<CivilleUserToCivilleUser> friendship = query.EndExecute(result).ToList();
                    if (friendship.Count == 0)
                    {
                        addAddFriendButton();
                    }
                });
        }

        private void OnLevelQueryCompleted(IAsyncResult result)
        {
            Dispatcher.BeginInvoke(() =>
                {
                    DataServiceQuery<Level> query = result.AsyncState as DataServiceQuery<Level>;
                    Level lvl = query.EndExecute(result).First();

                    //UserLevelControl.LevelProgressBar.Minimum = 0;
                    UserLevelControl.LevelProgressBar.Value = ((user.Points - user.LastLevelPoints) / (double)lvl.Points) * 100;
                    UserLevelControl.LevelProgressBar2.Value = ((user.Points - user.LastLevelPoints) / (double)lvl.Points) * 100;
                    UserLevelControl.LevelProgressBar3.Value = ((user.Points - user.LastLevelPoints) / (double)lvl.Points) * 100;
                    
                    //UserLevelControl.LevelProgressBar.Maximum = lvl.Points;
                    UserLevelControl.MaxPointsTextBlock.Text = lvl.Points.ToString();
                    UserLevelControl.NrPointsTextBlock.Text = (user.Points - user.LastLevelPoints).ToString();
                    UserLevelControl.MinPointsTextBlock.Text = "0";
                    UserLevelControl.LevelTextBlock.Text = "Level: " + lvl.ID;

                    CarbonTasksTxt.Text = "Carbon Tasks - " + user.CarbonType.ToString() + "/" + lvl.CarbonType.ToString() + " | Diamond Tasks - " + user.DiamondType.ToString() + "/" + lvl.DiamondType.ToString(); ;
                });
        }

        private void ApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Are you sure you want to add "+user.FirstName+" "+user.LastName+"?", "Add friend confirmation", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                CivilleUserToCivilleUser newFriendship = new CivilleUserToCivilleUser();
                newFriendship.UserID = UserContext.CurrentUser.ID;
                newFriendship.FriendID = user.ID;
                CivilleDataServiceConnector.CivilleContext.AddToCivilleUserToCivilleUsers(newFriendship);
                CivilleDataServiceConnector.CivilleContext.BeginSaveChanges(OnSaveChangesCompleted, CivilleDataServiceConnector.CivilleContext);
            }
        }
        //private void AddFriendButton_Click(object sender, RoutedEventArgs e)
        //{
        //    Dispatcher.BeginInvoke(() =>
        //    {
        //        CivilleUserToCivilleUser newFriendship = new CivilleUserToCivilleUser();
        //        newFriendship.UserID = UserContext.CurrentUser.ID;
        //        newFriendship.FriendID = user.ID;
        //        CivilleDataServiceConnector.CivilleContext.AddToCivilleUserToCivilleUsers(newFriendship);
        //        CivilleDataServiceConnector.CivilleContext.BeginSaveChanges(OnSaveChangesCompleted, CivilleDataServiceConnector.CivilleContext);
        //    });
        //}
        protected void OnSaveChangesCompleted(IAsyncResult result)
        {
            Dispatcher.BeginInvoke(() =>
                {
                    CivilleDataServiceConnector.CivilleContext.EndSaveChanges(result);                    
                    (ApplicationBar.Buttons[0] as ApplicationBarIconButton).IsEnabled = false;
                });
        }
    }
}
